<template>
  <div class="data-sync-container">
    <!-- 页面头部 -->
    <div class="page-header-content">
      <div class="flex-between mb-24">
        <div>
          <h3 style="margin: 0; color: #303133">数据同步任务</h3>
          <p style="margin: 8px 0 0; color: #909399">管理和监控数据源到 Doris 数据仓库的同步任务</p>
        </div>
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          创建同步任务
        </el-button>
      </div>

      <!-- 搜索和筛选 -->
      <div class="search-bar">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-input
              v-model="searchForm.name"
              placeholder="搜索任务名称"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.status" placeholder="任务状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="运行中" value="running" />
              <el-option label="成功" value="success" />
              <el-option label="失败" value="failed" />
              <el-option label="暂停" value="paused" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.syncType" placeholder="同步类型" clearable>
              <el-option label="全部" value="" />
              <el-option label="全量同步" value="full" />
              <el-option label="增量同步" value="incremental" />
              <el-option label="实时同步" value="realtime" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="taskList"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="任务名称" min-width="200">
          <template #default="{ row }">
            <div class="task-name-cell">
              <el-icon class="task-icon" :class="getTaskTypeClass(row.syncType)">
                <component :is="getTaskTypeIcon(row.syncType)" />
              </el-icon>
              <div>
                <div class="task-name">{{ row.name }}</div>
                <div class="task-desc">{{ row.description || '暂无描述' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="数据源" min-width="150">
          <template #default="{ row }">
            <div class="data-source-cell">
              <div class="source-item">
                <el-tag size="small" type="info">{{ row.sourceType }}</el-tag>
                <span class="source-name">{{ row.sourceName }}</span>
              </div>
              <el-icon class="arrow-icon"><ArrowRight /></el-icon>
              <div class="source-item">
                <el-tag size="small" type="success">Doris</el-tag>
                <span class="source-name">{{ row.targetTable }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="同步类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getSyncTypeTagType(row.syncType)" size="small">
              {{ getSyncTypeLabel(row.syncType) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              <el-icon style="margin-right: 4px">
                <component :is="getStatusIcon(row.status)" />
              </el-icon>
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="调度配置" width="120">
          <template #default="{ row }">
            <div v-if="row.isScheduled">
              <el-icon color="#67c23a"><Timer /></el-icon>
              <span style="font-size: 12px; margin-left: 4px">{{ row.cronExpression || '定时调度' }}</span>
            </div>
            <span v-else style="color: #909399; font-size: 12px">手动执行</span>
          </template>
        </el-table-column>

        <el-table-column label="最近执行" min-width="180">
          <template #default="{ row }">
            <div v-if="row.lastExecution" class="execution-info">
              <div class="execution-time">{{ formatTime(row.lastExecution.startTime) }}</div>
              <div class="execution-details">
                <span class="success-count">成功: {{ row.lastExecution.successRecords || 0 }}</span>
                <span class="failed-count" v-if="row.lastExecution.failedRecords">
                  失败: {{ row.lastExecution.failedRecords }}
                </span>
                <span class="duration">耗时: {{ formatDuration(row.lastExecution.duration) }}</span>
              </div>
            </div>
            <span v-else style="color: #909399">未执行</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tooltip content="立即执行">
                <el-button type="primary" size="small" circle @click="handleExecute(row)">
                  <el-icon><VideoPlay /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip content="查看日志">
                <el-button type="info" size="small" circle @click="handleViewLogs(row)">
                  <el-icon><Document /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip content="编辑">
                <el-button type="warning" size="small" circle @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip content="删除">
                <el-button type="danger" size="small" circle @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-dropdown @command="(cmd) => handleMoreAction(cmd, row)">
                <el-button size="small" circle>
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="pause" v-if="row.status === 'running'">
                      <el-icon><VideoPause /></el-icon>
                      暂停任务
                    </el-dropdown-item>
                    <el-dropdown-item command="resume" v-if="row.status === 'paused'">
                      <el-icon><VideoPlay /></el-icon>
                      恢复任务
                    </el-dropdown-item>
                    <el-dropdown-item command="clone">
                      <el-icon><CopyDocument /></el-icon>
                      克隆任务
                    </el-dropdown-item>
                    <el-dropdown-item command="export">
                      <el-icon><Download /></el-icon>
                      导出配置
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 批量操作栏 -->
    <div v-if="selectedTasks.length > 0" class="batch-actions">
      <el-card class="batch-card">
        <div class="flex-between">
          <span>已选择 {{ selectedTasks.length }} 个任务</span>
          <div class="action-buttons">
            <el-button type="primary" @click="handleBatchExecute">
              <el-icon><VideoPlay /></el-icon>
              批量执行
            </el-button>
            <el-button type="warning" @click="handleBatchPause">
              <el-icon><VideoPause /></el-icon>
              批量暂停
            </el-button>
            <el-button type="danger" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 执行日志对话框 -->
    <LogDialog 
      v-model="logDialogVisible" 
      :task-id="currentTaskId"
      @close="logDialogVisible = false" 
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import LogDialog from './components/LogDialog.vue'
import { formatTime, formatDuration } from '@/utils/date'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const taskList = ref([])
const selectedTasks = ref([])
const logDialogVisible = ref(false)
const currentTaskId = ref(null)

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  syncType: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 生命周期
onMounted(() => {
  fetchTaskList()
})

// 方法
const fetchTaskList = async () => {
  loading.value = true
  try {
    // 模拟 API 调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟数据
    taskList.value = [
      {
        id: 1,
        name: '用户订单数据同步',
        description: '从 MySQL 同步用户订单数据到 Doris 数据仓库',
        sourceType: 'MySQL',
        sourceName: 'orders_db.orders',
        targetTable: 'fact_orders',
        syncType: 'incremental',
        status: 'running',
        isScheduled: true,
        cronExpression: '0 */2 * * *',
        lastExecution: {
          startTime: new Date(Date.now() - 3600000),
          successRecords: 15420,
          failedRecords: 0,
          duration: 125
        }
      },
      {
        id: 2,
        name: '商品信息全量同步',
        description: '从 PostgreSQL 全量同步商品信息',
        sourceType: 'PostgreSQL',
        sourceName: 'product_db.products',
        targetTable: 'dim_products',
        syncType: 'full',
        status: 'success',
        isScheduled: true,
        cronExpression: '0 2 * * *',
        lastExecution: {
          startTime: new Date(Date.now() - 86400000),
          successRecords: 8765,
          failedRecords: 0,
          duration: 45
        }
      },
      {
        id: 3,
        name: '实时点击流数据',
        description: '从 Kafka 实时同步用户行为数据',
        sourceType: 'Kafka',
        sourceName: 'clickstream_topic',
        targetTable: 'fact_clickstream',
        syncType: 'realtime',
        status: 'failed',
        isScheduled: false,
        lastExecution: {
          startTime: new Date(Date.now() - 1800000),
          successRecords: 0,
          failedRecords: 1000,
          duration: 5
        }
      }
    ]
    
    pagination.total = 3
  } catch (error) {
    ElMessage.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

const handleCreate = () => {
  router.push('/data-sync/create')
}

const handleEdit = (row) => {
  router.push(`/data-sync/edit/${row.id}`)
}

const handleExecute = (row) => {
  ElMessageBox.confirm(
    `确认立即执行同步任务 "${row.name}"？`,
    '确认执行',
    {
      confirmButtonText: '执行',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('任务执行成功')
    fetchTaskList()
  }).catch(() => {})
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除同步任务 "${row.name}"？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('删除成功')
    fetchTaskList()
  }).catch(() => {})
}

const handleViewLogs = (row) => {
  currentTaskId.value = row.id
  logDialogVisible.value = true
}

const handleMoreAction = (command, row) => {
  switch (command) {
    case 'pause':
      ElMessage.success('任务已暂停')
      break
    case 'resume':
      ElMessage.success('任务已恢复')
      break
    case 'clone':
      ElMessage.success('任务克隆成功')
      break
    case 'export':
      ElMessage.success('配置导出成功')
      break
  }
  fetchTaskList()
}

const handleSearch = () => {
  pagination.page = 1
  fetchTaskList()
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  searchForm.syncType = ''
  handleSearch()
}

const handleSelectionChange = (selection) => {
  selectedTasks.value = selection
}

const handleSizeChange = () => {
  fetchTaskList()
}

const handleCurrentChange = () => {
  fetchTaskList()
}

// 批量操作
const handleBatchExecute = () => {
  ElMessage.success(`批量执行 ${selectedTasks.value.length} 个任务`)
}

const handleBatchPause = () => {
  ElMessage.success(`批量暂停 ${selectedTasks.value.length} 个任务`)
}

const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确认删除选中的 ${selectedTasks.value.length} 个任务？`,
    '批量删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('批量删除成功')
    selectedTasks.value = []
    fetchTaskList()
  }).catch(() => {})
}

// 工具方法
const getTaskTypeIcon = (type) => {
  const icons = {
    'full': 'Download',
    'incremental': 'Refresh',
    'realtime': 'Connection'
  }
  return icons[type] || 'Connection'
}

const getTaskTypeClass = (type) => {
  const classes = {
    'full': 'full-sync',
    'incremental': 'incremental-sync',
    'realtime': 'realtime-sync'
  }
  return classes[type] || ''
}

const getSyncTypeLabel = (type) => {
  const labels = {
    'full': '全量同步',
    'incremental': '增量同步',
    'realtime': '实时同步'
  }
  return labels[type] || type
}

const getSyncTypeTagType = (type) => {
  const types = {
    'full': 'info',
    'incremental': 'warning',
    'realtime': 'success'
  }
  return types[type] || 'info'
}

const getStatusLabel = (status) => {
  const labels = {
    'running': '运行中',
    'success': '成功',
    'failed': '失败',
    'paused': '暂停'
  }
  return labels[status] || status
}

const getStatusTagType = (status) => {
  const types = {
    'running': 'primary',
    'success': 'success',
    'failed': 'danger',
    'paused': 'warning'
  }
  return types[status] || 'info'
}

const getStatusIcon = (status) => {
  const icons = {
    'running': 'Loading',
    'success': 'CircleCheck',
    'failed': 'CircleClose',
    'paused': 'VideoPause'
  }
  return icons[status] || 'QuestionFilled'
}
</script>

<style scoped>
.data-sync-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header-content {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.search-bar {
  margin-top: 16px;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
}

.table-card :deep(.el-table) {
  flex: 1;
}

.task-name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-icon {
  font-size: 20px;
  color: #409eff;
}

.task-icon.full-sync {
  color: #909399;
}

.task-icon.incremental-sync {
  color: #e6a23c;
}

.task-icon.realtime-sync {
  color: #67c23a;
}

.task-name {
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}

.task-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.data-source-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.source-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

.source-name {
  font-size: 12px;
  color: #606266;
}

.arrow-icon {
  color: #c0c4cc;
}

.execution-info {
  font-size: 12px;
}

.execution-time {
  color: #303133;
  margin-bottom: 4px;
}

.execution-details {
  display: flex;
  gap: 8px;
  color: #909399;
}

.success-count {
  color: #67c23a;
}

.failed-count {
  color: #f56c6c;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.pagination-container {
  padding: 16px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

.batch-actions {
  position: fixed;
  bottom: 24px;
  left: 264px;
  right: 24px;
  z-index: 1000;
}

.batch-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

@media (max-width: 768px) {
  .batch-actions {
    left: 24px;
  }
}
</style> 